<?php
if(!defined('IN_BSTO')){ die('[ERROR] You cannot load this page directly !!!'); }

/**
 * @author hungvjnh, tuhuy, tuananh
 * 
 */

//define('TWITTER_COUNTER_URL', 'http://urls.api.twitter.com/1/urls/count.json?url=');    

define('TWITTER_COUNTER_URL', 'http://search.twitter.com/search.json?q=');
define('TWITTER_RESULT_TYPE', 'recent');

//define('PYCOOL_BASE_URL', 'http://demo3.pyramid-consulting.com/intershipphp2/1.0/detail/');

define('TWITTER_MAX_PAGE', 15);
define('TWITTER_MAX_RESULT_PER_PAGE', 100);

define('TWITTER_RETWEET_PREFIX', 'RT @');
    
// Debug mode
define('DEBUG_MODE', false);

// Log cronjob mode
define('LOG_CRON_MODE', true);

// Facebook Statistic Enabled/ Disabled
define('ENABLED_FACEBOOK_MODE', true);

// Twitter Statistic Enabled/ Disabled
define('ENABLED_TWITTER_MODE', true);


class CronLSTR{
    private $statisticURL = '';
    
    private $db = null;
    private $facebook = null;

    private $errors = array();
    
    function __construct()
    {
        $this->db = new DB();
        
        $this->statisticURL = $this->db->get('configManager')->statisticURL;
        
        $this->db->startConnection();
    }
    
    function __destruct()
    {
        $this->db->closeConnection();
    }
    
    /**
     * connect facebook
     */
    private function connectFacebook()
    {
        $config = $this->db->get('configManager');
        
        $fbex = array(
          'appId'  => $config->appID,
          'secret' => $config->appSecret,
          'cookie' => true
        );
        
        require '../lib/facebook_sdk/facebook.php';
        
        $this->facebook = new Facebook($fbex);

    }
    
    /**
     * getFacebookStatistic of a book
     */
     
    private function getFacebookStatistic($id)
    {
        $url = $this->statisticURL . 'detail/' . $id;
        echo $url;
        if(DEBUG_MODE){
            echo " > getFacebookStatistic(" . $url . ");<br />";
        }
        
        $link_stat_query = 'SELECT  normalized_url, 
                                    share_count, 
                                    like_count, 
                                    comment_count, 
                                    total_count, 
                                    commentsbox_count, 
                                    comments_fbid 
                            FROM link_stat 
                            WHERE url="'.$url.'"';
        $params = array(
    	    'method' => 'fql.query',
    	    'query' => $link_stat_query);
    
        $fqlResult = $this->facebook->api($params);
        
        return $fqlResult[0];            
    }
    
    /**
     * getFacebookStatistics of all books
     */
    
    private function getFacebookStatistics()
    {
        $arrId = $this->db->get('bookManager')->getBookId();

        foreach($arrId as $ele){
            $result = $this->getFacebookStatistic($ele['nid']);
            
            echo  $this->bookURL . $ele['nid'] .  "|" . $result['like_count'] . "|" . $result['share_count'] . "<br />";  
        }
    }
    
    /**
     * getTwitterStatistic of a book
     */
    
    
    /**
     * get Total Retweets of a Search Results
     */
    private function getRetweet($dts){
        
        if($dts === null){
            $dts = array();
        }
        
        $count = 0;
        
        foreach($dts as $dt){
            $firstKey = substr($dt->text, 0, 4);
            if($firstKey == TWITTER_RETWEET_PREFIX){
                $count++;
            } 
        }
        if(DEBUG_MODE){
            echo " > getRetweet(dts); <br /> - result: " . $count . "<br />";
        }
        return $count;
    }

    /**
     * get a result page of a URL
     */
    private function getTwitterPageInfo($url, $page, $ifSince){

        $contentURL = TWITTER_COUNTER_URL . $url . '&result_type=' . TWITTER_RESULT_TYPE . '&rpp=' . TWITTER_MAX_RESULT_PER_PAGE . '&page=' . $page . $ifSince;
                
        $content = file_get_contents($contentURL);
        
        $data = json_decode($content);

        //echo checkTotalResults($data);
        if(DEBUG_MODE){
            echo "> getTwitterPageInfo(" . $contentURL . ", " . $page . ", " . ($ifSince == null ? "null" : $ifSince) . ");<br />";
        }
        if(DEBUG_MODE){
            var_dump($data);
        }

        return $data;
    }   
    
    /**
     * get twitter info a a url
     */
    private function searchTwitter($id, $since)
    {
        $url = $this->statisticURL . 'detail/' . $id;
        
        if(DEBUG_MODE){
            echo " > searchTwitter(" . $url . ", ". ($since == null ? "null" : $since ) . "); <br />";
        }
        
        if($since != null){
            $ifSince = '&since_id=' . $since;
        }
        else {
            $ifSince = '';
        }
        
        $data = $this->getTwitterPageInfo($url, 1, $ifSince);
        
        $count = count($data->results);
        
        // maxId is maxId of first page(result_type =  recent)
        $maxId = $data->max_id_str;
        $result = $this->getRetweet($data->results);
        
        if($count < TWITTER_MAX_RESULT_PER_PAGE){
            return array('max_id' => $maxId, 'result' => $result);
        }
        else {
            $i = 2;
            $data = $this->getTwitterPageInfo($url, $i, $ifSince);
            $count = count($data->results);
            $result += $this->getRetweet($data->results);
            
            while($count == TWITTER_MAX_RESULT_PER_PAGE && $i <= TWITTER_MAX_PAGE){
                $i++;
                $data = $this->getTwitterPageInfo($url, $i, $ifSince);
                $count = count($data->results);
                $result += $this->getRetweet($data->results);
            }
            
            return array('max_id' => $maxId, 'result' => $result);
        }
    }
    
    /**
     * main function: get Twitter statistic of a url
     */
    public function getTwitterStatistic($id){
        // TODO: get since_id from db
        $query = "SELECT `since_id` FROM `plugin` WHERE nid=".$id." AND `date` = (SELECT MAX(`date`) FROM `plugin` WHERE plugin.nid=".$id." AND DATE(`date`) != DATE(NOW()))";
        $sinceId = $this->db->getArrayData($query); 

        $since = $sinceId[0]['since_id'];
        
        if(DEBUG_MODE){
            echo "> dbQuery(".$query.");<br />";
            echo " - result: " . ($since == null ? "null" : $since) . "<br />";
        }
        
        $data = $this->searchTwitter($id, $since);

        return $data;
    }
    
    
    /**
     * save statistics to db
     */
    private function saveStatistic($nid, $like, $share, $retweet)
    {
        if(DEBUG_MODE){
            echo " > saveStatistic(" . $nid . ", " . $like . ", " . $share . ", " . print_r($retweet, true) . "); <br />";
        }
        
        if(!isset($nid) || !isset($like) || !isset($share) || !isset($retweet) || !isset($retweet['result']) || !isset($retweet['max_id'])){
            echo "[ERROR] saveStatistic fail !";
            return false;
        }
        
        $query  = 'SELECT `nid`, `retweet` FROM `plugin` WHERE `nid`='.$nid.' AND DATE(`date`) = DATE(NOW())';//check if the current date exists
        $result = $this->db->getArrayData($query);
                
        $count = count($result);
        
        if(DEBUG_MODE){
            echo " > dbQuery(".$query.");<br />";
            echo " - result : " . $count . "<br />";
        }
        
        // get retweet yesterday
        $query2  = 'SELECT `nid`, `retweet` FROM `plugin` WHERE `nid`='.$nid.' AND `date` = (SELECT MAX(`date`) FROM `plugin` WHERE plugin.nid = '.$nid.' AND DATE(`date`) != DATE(NOW()))';//check if the current date exists
        $result2 = $this->db->getArrayData($query2);
        $count2 = count($result2);
        
        
        // add to total retweets
        if($count2 == 0){
            $add = 0;
        }
        else {
            $add = $result2[0]['retweet'];
        }
        $retweet['result'] += intval($add);
        
        if($count == 0){
            $query = 'INSERT INTO `plugin` (`nid`, `like`, `share`,`retweet`, `since_id`, `date`) VALUES ('. $nid .','. $like .',' .  $share.','.$retweet['result'].', ' .$retweet['max_id'] .', NOW() )';
            $this->db->dbQuery($query); 
        }
        else{
            $query = 'UPDATE `plugin` SET `like` = ' . $like . ' , `share`=' . $share . ', `retweet`=' . $retweet['result'] . ', `since_id`='.$retweet['max_id'].' WHERE `nid`=' . $nid . ' AND DATE(`date`) = DATE(NOW())';
            $this->db->dbQuery($query);
        }
          
        if(DEBUG_MODE){
            echo " > dbQuery(".$query.");<br />";
        }
    }
    
    /**
     * get fb & twitter statistics
     */
    private function getSocialStatistic()
    {
        $arrId = $this->db->get('bookManager')->getBookId();
        
        if(LOG_CRON_MODE){
            $logContent = array();
        }
        
        foreach($arrId as $ele){
            //$errors = array();
            $error = '';
            
            if(ENABLED_FACEBOOK_MODE){
                $facebook = $this->getFacebookStatistic($ele['nid']);

                if(!isset($facebook) || !$facebook){
                    $error .= "[Facebook connection error]";
                    echo $error;
                    //array_push($errors, $error);
                }
            }
            else {
                $facebook['share_count'] = 0;
                $facebook['like_count'] = 0;
            }
            
            
            if(ENABLED_TWITTER_MODE){
                $twitter = $this->getTwitterStatistic($ele['nid']);
            
                if(!isset($twitter) || !$twitter){
                    $error .=  "[Twitter connection error]";
                    echo $error;
                    //array_push($errors, $error);
                }
            }
            else {
                $twitter['result'] = 0;
                $twitter['max_id'] = ''; 
                
            }
            
            
            // save results to db
            $handle = $this->saveStatistic($ele['nid'], $facebook['like_count'], $facebook['share_count'], $twitter);
            
            
            if(LOG_CRON_MODE){
                if($error == ''){
                    $error = 'Success';
                }
                $array = array('nid'    => $ele['nid'],
                            'like'      => $facebook['like_count'],
                            'share'     => $facebook['share_count'],
                            'retweet'   => $twitter['result'],
                            'error'     => $error);
                echo "[GET] " . $ele['nid'] .  " > " . $facebook['like_count'] . "|" . $facebook['share_count'] . "|" . $twitter['result'] . " > " .$error . "<br />";
                
                array_push($logContent, $array);
                //break;
                
            }
            
            if(DEBUG_MODE){
                //echo "[GET] " . $ele['nid'] .  " > " . $facebook['like_count'] . "|" . $facebook['share_count'] . "|" . $twitter['result'] . "<br />";
                break;
            }       
        }
        
        if(LOG_CRON_MODE){
            //var_dump($logContent);
            return $logContent;
        }
        else {
            return true;
        }
    }
    
    
    /**
     * update counter
     */
    private function updateCounter()
    {      
        //Update total
        $query = 'UPDATE `plugin` SET `total` = `like`+`share`+`retweet` WHERE DATE(`date`) = DATE(NOW())';
        $this->db->dbQuery($query);

        //Update point
        $query = 'UPDATE `book` SET `point` = (SELECT `like` 
                                                FROM `plugin` 
                                                WHERE plugin.nid=book.nid
                                                    AND `date` = (SELECT MAX(`date`) 
                                                                    FROM `plugin` 
                                                                    WHERE plugin.nid=book.nid))
                                            *(SELECT `value` 
                                                FROM `configuration` 
                                                WHERE `key` = "A")';
        $this->db->dbQuery($query); 
        
        $query = 'UPDATE `book` SET `point` = (SELECT `share` 
                                                FROM `plugin` 
                                                WHERE plugin.nid=book.nid 
                                                    AND `date` = (SELECT MAX(`date`) 
                                                                        FROM `plugin` 
                                                                        WHERE plugin.nid=book.nid))
                                            *(SELECT `value` 
                                                FROM `configuration` 
                                                WHERE `key` = "B")
                                            +`point`';
        $this->db->dbQuery($query); 
        
        
        $query = 'UPDATE `book` SET `point` = (SELECT `retweet` 
                                                FROM `plugin` 
                                                WHERE plugin.nid=book.nid
                                                    AND `date` = (SELECT MAX(`date`) 
                                                                            FROM `plugin` 
                                                                            WHERE plugin.nid=book.nid))
                                            *(SELECT `value` 
                                                FROM `configuration` 
                                                WHERE `key` = "C")
                                            +`point`';
        $this->db->dbQuery($query);
        
    }
    
    public function testGetTwitter()
    {
        for($i = 1; $i <=15; $i++){
            $data = $this->getTwitterPageInfo('css-tricks.com', $i, '');
        }
    }
    
    public function test(){
        
    }
    
    /**
     * run the statistics
     */
    public function run()
    {
        if(ENABLED_FACEBOOK_MODE){
            $this->connectFacebook();
        }
        
        $content = $this->getSocialStatistic();
        
        $this->updateCounter();
        
        return $content;
    }
}


    
?>